package com.las.bot.cmd.wordcup;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.OSSClient;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.las.annotation.BotCmd;
import com.las.bot.cmd.wx.YiQingWxCmd;
import com.las.bot.cmd.xf.XFSCommand;
import com.las.bot.common.Constant;
import com.las.bot.dao.WcGroupDao;
import com.las.bot.dao.WcGroupNumDao;
import com.las.bot.dao.WcOrderDao;
import com.las.cmd.BaseCommand;
import com.las.config.AppConfigs;
import com.las.utils.StrUtils;
import com.las.utils.mirai.CmdUtil;
import com.model.WcGroup;
import com.model.WcGroupNum;
import com.model.WcOrder;
import com.utils.*;
import com.utils.worldcup.WorldCupOrderUtils;
import com.utils.worldcup.WorldCupUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.*;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@BotCmd(funName = "世界杯")
public class WorldCupOrderCmd extends BaseCommand {

    private Logger logger = LoggerFactory.getLogger(WorldCupOrderCmd.class);

    private ThreadPoolExecutor executor = ThreadUtil.getPool();

    @Autowired
    private WcOrderDao orderDao;


    public WorldCupOrderCmd() {
        super("串门", "串门2", "串门3");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String cmd, ArrayList<String> args) throws Exception {
        if (args.size() > 5) {
            String winStr = args.get(0);
            String lostStr = args.get(2);
            String ppStr = args.get(1);
            String winStr2 = args.get(3);
            String lostStr2 = args.get(5);
            String ppStr2 = args.get(4);
            if (!StrUtils.isNumeric(winStr) || !StrUtils.isNumeric(lostStr) || !StrUtils.isNumeric(ppStr)) {
                CmdUtil.sendMessage("请在指令后面带6个整数", userId, id, type);
                return;
            }
            if (!StrUtils.isNumeric(winStr2) || !StrUtils.isNumeric(lostStr2) || !StrUtils.isNumeric(ppStr2)) {
                CmdUtil.sendMessage("请在指令后面带6个整数", userId, id, type);
                return;
            }

            int win = Integer.parseInt(winStr);
            int lost = Integer.parseInt(lostStr);
            int pp = Integer.parseInt(ppStr);
            int win2 = Integer.parseInt(winStr2);
            int lost2 = Integer.parseInt(lostStr2);
            int pp2 = Integer.parseInt(ppStr2);
            int all = win + lost + pp + win2 + lost2 + pp2;
            if (all == 0) {
                CmdUtil.sendMessage("指令后面6个整数不能全部是0", userId, id, type);
                return;
            }
            List<Integer> nums = Lists.newArrayList(win, lost, pp, win2, lost2, pp2);
            List<Integer> collect = nums.stream().filter(a -> a > 0)
                    .sorted((o1, o2) -> o2 - o1)
                    .collect(Collectors.toList());
            Integer a = collect.get(0);
            if (a < 2) {
                CmdUtil.sendMessage("指令后面6个整数只能是2 or 0", userId, id, type);
                return;
            }

            // 实现准备好空集合
            ArrayList<String> urls = new ArrayList<>();
            synchronized (orderDao) {
                try {
                    int index = 0;
                    if (cmd.contains("串门2")) {
                        index = 1;
                    } else if (cmd.contains("串门3")) {
                        index = 2;
                    }
                    // 开始计算
                    boolean isUpdate = setWcOrder(index);
                    if (isUpdate) {
                        CmdUtil.sendMessage("数据已更新", userId, id, type);
                    } else {
                        CmdUtil.sendMessage("数据暂无变化！过一会可能会变哦~", userId, id, type);
                    }
                    String order = goRun(win, lost, pp, win2, lost2, pp2);
                    executor.execute(() -> {
                        String[] split = order.split("\\n");
                        String uuid = genImg(split);

                        String fileName = uuid + ".png";
                        File file = new File(fileName);
                        try {
                            String objectName = uuid + Constant.BUCKET_PNG;
                            // 下一步将目标图上传到阿里云
                            String endpoint = Constant.HTTPS + Constant.OSS;
                            String accessKeyId = Constant.BUCKET_ID;
                            String accessKeySecret = Constant.BUCKET_KEY;
                            String bucketName = Constant.BUCKET_NAME;
                            // 上传到阿里云OSS
                            OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
                            ossClient.putObject(bucketName, objectName, file);
                            ossClient.shutdown();
                            String imgUrl = Constant.HTTPS + Constant.BUCKET_NAME + "." + Constant.OSS + objectName;
                            urls.add(imgUrl);
                            if (CollectionUtil.isNotEmpty(urls)) {
                                if (type == Constant.MESSAGE_TYPE_GROUP) {
                                    CmdUtil.sendImgMessage(urls, userId, id, Constant.MESSAGE_TYPE_DISCUSS);
                                    CmdUtil.sendAtMessage("方案已私聊发你啦~\n注：若没收到消息，可以先检查和机器人开临时会话聊天试试！", userId, userId, id, type);
                                } else {
                                    CmdUtil.sendImgMessage(urls, userId, id, type);
                                }
                            }
                        } catch (Exception e) {
                            CmdUtil.sendMessage("生成图片失败...请稍后再试...", userId, id, type);
                        } finally {
                            // 上传成功后需要删除本地图
                            if (file.exists()) {
                                file.delete();
                            }
                        }
                    });
                } catch (Exception e) {
                    logger.error("模拟下注出现异常，请检查参数");
                }
            }
        } else {
            CmdUtil.sendMessage("请在指令后面带6个整数", userId, id, type);
        }

    }

    private String goRun(int win, int lost, int pp, int win2, int lost2, int pp2) {
        WcOrder wcOrder = orderDao.findByRecent();
        String event = wcOrder.getEvent();
        String[] eventA = event.split("#");
        List<String> groupA = Lists.newArrayList();
        for (String e : eventA) {
            String[] vs = e.split("VS");
            groupA.add(vs[0]);
            groupA.add(vs[1]);
        }
        double[] scoreA = new double[4];
        double[] scoreB = new double[4];
        String sourceA = wcOrder.getSourceA();
        String[] asp = sourceA.split(",");
        for (int i = 0; i < asp.length; i++) {
            scoreA[i] = Double.parseDouble(asp[i]);
        }

        String sourceB = wcOrder.getSourceB();
        String[] bsp = sourceB.split(",");
        for (int i = 0; i < bsp.length; i++) {
            scoreB[i] = Double.parseDouble(bsp[i]);
        }

        Map<String, Object> orderMap = WorldCupOrderUtils.getInstance().getOrder(win, lost, pp, win2, lost2, pp2, groupA, eventA, scoreA, scoreB);
        return orderMap.get("result").toString();

    }

    private static String genImg(String[] split) {
        int width = 450;
        int height = 950;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);//设置宽高，图片类型
        Graphics g = image.getGraphics();
        g.setClip(0, 0, width, height);//设置绘画的区域,默认背景是黑色，也叫做获取画笔，指定画笔可画的范围
        g.setColor(Color.white);//设置画笔颜色
        g.fillRect(0, 0, width, height);//画一个矩形块,颜色是白色，因为画笔颜色是白色
        g.setColor(Color.black);//设置画笔颜色
        g.setFont(new Font("宋体", Font.PLAIN, 22));//设计字体样式
        for (int i = 0; i < split.length; i++) {
            String str = split[i];
            g.drawString(str, 35, 25 * (i + 1));
        }
        g.dispose();
        String fileId = StrUtils.uuid();
        try {
            ImageIO.write(image, "png", new File(fileId + ".png"));
        } catch (IOException ignored) {
        }
        return fileId;
    }

    private boolean setWcOrder(int index) throws Exception {
        boolean tag = false;
        String ymd = DateUtils.formatYMD(new Date());
        String url = "https://trade.500.com/jczq/?playid=354&g=2&vtype=nspf&date=" + ymd;
        Document document = Jsoup.parse(new URL(url), 30000);
        List<Element> list = document.getElementsByClass("betbtn-row itm-rangB1");
        List<Element> teamList = document.getElementsByClass("team");
        Element team1 = teamList.get(index + 1);
        String team1Str = SpiderHtml.guoHtml(team1.text()).trim();
        Element team2 = teamList.get(index + 2);
        String team2Str = SpiderHtml.guoHtml(team2.text()).trim();
        List<String> teamNames = Lists.newArrayList();
        if (team1Str.contains("VS") && team2Str.contains("VS")) {
            String[] tsp = team1Str.split("VS");
            String s1 = tsp[0].trim().replaceAll("\\d+", "").replaceAll("\\[", "").replaceAll("]", "");
            String s2 = tsp[1].trim().replaceAll("\\d+", "").replaceAll("\\[", "").replaceAll("]", "");
            teamNames.add(s1);
            teamNames.add(s2);

            String[] tsp2 = team2Str.split("VS");
            String s3 = tsp2[0].trim().replaceAll("\\d+", "").replaceAll("\\[", "").replaceAll("]", "");
            String s4 = tsp2[1].trim().replaceAll("\\d+", "").replaceAll("\\[", "").replaceAll("]", "");
            teamNames.add(s3);
            teamNames.add(s4);
        }

        String teamEvent = "";
        if (CollectionUtil.isNotEmpty(teamNames)) {
            Element element1 = list.get(index);
            String c1 = SpiderHtml.guoHtml(element1.text());
            String[] sp1 = c1.split(" ");
            double v1 = Double.parseDouble(sp1[0]);
            double max1 = 0.0;
            double min1 = 0.0;
            double mid1 = 0.0;
            if (sp1.length == 3) {
                double v2 = Double.parseDouble(sp1[2]);
                max1 = v1 > v2 ? v1 : v2;
                min1 = v1 < v2 ? v1 : v2;
                mid1 = Double.parseDouble(sp1[1]);
                if (v1 > v2) {
                    //team1的名字 1 和 2 对调
                    teamEvent = teamNames.get(1) + "VS" + teamNames.get(0) + "#";
                } else {
                    teamEvent = teamNames.get(0) + "VS" + teamNames.get(1) + "#";
                }
            }

            Element element2 = list.get(index + 1);
            String c2 = SpiderHtml.guoHtml(element2.text());
            String[] sp2 = c2.split(" ");
            double vv1 = Double.parseDouble(sp2[0]);
            double max2 = 0.0;
            double min2 = 0.0;
            double mid2 = 0.0;
            if (sp2.length == 3) {
                double vv2 = Double.parseDouble(sp2[2]);
                max2 = vv1 > vv2 ? vv1 : vv2;
                min2 = vv1 < vv2 ? vv1 : vv2;
                mid2 = Double.parseDouble(sp2[1]);
                if (vv1 > vv2) {
                    //team2的名字 对调
                    teamEvent += teamNames.get(3) + "VS" + teamNames.get(2);
                } else {
                    teamEvent += teamNames.get(2) + "VS" + teamNames.get(3);
                }
            }
            if (max1 > 0 && max2 > 0) {
                String sourceA = min1 + "," + max1 + "," + min2 + "," + max2;
                String sourceB = mid1 + "," + mid1 + "," + mid2 + "," + mid2;
                WcOrder wcOrder = orderDao.findByRecent();
                if (!wcOrder.getSourceA().equals(sourceA) || !wcOrder.getSourceB().equals(sourceB)) {
                    tag = true;
                    wcOrder.setId(null);
                    wcOrder.setSourceA(sourceA);
                    wcOrder.setSourceB(sourceB);
                    wcOrder.setEvent(teamEvent);
                    orderDao.saveOrUpdate(wcOrder);
                }
            }
        }
        return tag;
    }


}
